package com.cloudeasy.api.util;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.vo.Result;
import org.springframework.beans.BeanUtils;

/**
 * {@link Result}工具类
 */
public class ResultUtil {

    /**
     * 返回无数据的成功{@link Result<T>}
     *
     * @param <T> 结果泛型
     * @return 成功 {@link Result<T>}
     */
    public static <T> Result<T> success() {
        Result<T> result = new Result<>();
        result.setFlag(Boolean.TRUE)
                .setCode(ResultCodeEnum.SUCCESS.getCode())
                .setMessage(ResultCodeEnum.SUCCESS.getMessage());
        return result;
    }

    /**
     * 返回有数据的成功 {@link Result<T>}
     *
     * @param <T>  结果泛型
     * @param data {@link T}类型的数据
     * @return 成功 {@link Result<T>}
     */
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setFlag(Boolean.TRUE)
                .setCode(ResultCodeEnum.SUCCESS.getCode())
                .setMessage(ResultCodeEnum.SUCCESS.getMessage())
                .setData(data);
        return result;
    }

    /**
     * 返回由{@link ResultCodeEnum}构造的失败 {@link Result<T>}
     *
     * @param <T>            结果泛型
     * @param resultCodeEnum {@link ResultCodeEnum}类型的数据
     * @return 失败 {@link Result<T>}
     */
    public static <T> Result<T> failure(ResultCodeEnum resultCodeEnum) {
        Result<T> result = new Result<>();
        result.setFlag(Boolean.FALSE)
                .setCode(resultCodeEnum.getCode())
                .setMessage(resultCodeEnum.getMessage());
        return result;
    }

    /**
     * 返回由{@link CloudEasyException}构造的失败 {@link Result<T>}
     *
     * @param <T> 结果泛型
     * @param e   {@link CloudEasyException}类型的数据
     * @return 失败 {@link Result<T>}
     */
    public static <T> Result<T> failure(CloudEasyException e) {
        Result<T> result = new Result<>();
        result.setFlag(Boolean.FALSE)
                .setCode(e.getCode())
                .setMessage(e.getMessage());
        return result;
    }

    /**
     * 返回失败 {@link Result<T>}
     *
     * @param <T>     结果泛型
     * @param message 错误消息
     * @return 失败 {@link Result<T>}
     */
    public static <T> Result<T> failure(String message) {
        Result<T> result = new Result<>();
        result.setFlag(Boolean.FALSE)
                .setCode(ResultCodeEnum.ERROR.getCode())
                .setMessage(message);
        return result;
    }

    /**
     * 转换为{@link Result<T>}
     *
     * @param result 原始{@link Result}
     * @param <T>    结果泛型
     * @return {@link Result<T>}
     */
    public static <T> Result<T> convert(Result result) {
        Result<T> temp = new Result<>();
        BeanUtils.copyProperties(result, temp);
        return temp;
    }
}
